<template>
  <div class="wrapper">
    <!-- header部分 -->
    <header>
      <p>在线支付</p>
    </header>
    <!-- 订单信息部分 -->
    <h3>订单信息：</h3>
    <div class="order-info">
      <p>
        {{ business.businessName }}
        <i class="fa fa-caret-down" @click="detailetShow"></i>
      </p>
      <p>&#165;{{ totalPrice }}</p>
    </div>
    <!-- 订单明细部分 -->
    <ul class="order-detailet" v-show="isShowDetailet">
      <li v-for="item in this.orderDetails">
        <p>{{ item.food.foodName }} x {{ item.quantity }}</p>
        <p>&#165;{{ item.food.foodPrice * item.quantity }}</p>
      </li>
      <li>
        <p>配送费</p>
        <p>&#165;{{ business.deliveryPrice }}</p>
      </li>
    </ul>
    <!-- 支付方式部分 -->
    <ul class="payment-type">
      <li @click="selectedPaymentMethod = 1">
        <div class="payment-option">
          <i class="fa fa-wallet"></i>
          <div class="payment-info">
            <div class="payment-title">余额支付</div>
            <div class="payment-desc">使用账户余额支付</div>
          </div>
        </div>
        <i v-if="selectedPaymentMethod === 1" class="fa fa-check-circle"></i>
      </li>
      <li @click="selectedPaymentMethod = 2">
        <div class="payment-option">
          <i class="fa fa-credit-card"></i>
          <div class="payment-info">
            <div class="payment-title">透支支付</div>
            <div class="payment-desc">使用透支额度支付</div>
          </div>
        </div>
        <i v-if="selectedPaymentMethod === 2" class="fa fa-check-circle"></i>
      </li>
    </ul>
    <div class="payment-button" @click="toPay()">
      <button>确认支付</button>
    </div>
    <!-- 底部菜单部分 -->
    <footer class="bottom-nav">
      <div class="nav-item" :class="{ active: $route.path === '/index' }" @click="$router.push('/index')">
        <i class="fa fa-home"></i>
        <span>首页</span>
      </div>
      <div class="nav-item">
        <i class="fa fa-compass"></i>
        <span>商家</span>
      </div>
      <div class="nav-item" :class="{ active: $route.path === '/orderList' }" @click="$router.push('/orderList')">
        <i class="far fa-file-alt"></i>
        <span>订单</span>
      </div>
      <div class="nav-item" :class="{ active: $route.path === '/userProfile' }" @click="$router.push('/userProfile')">
        <i class="fa fa-user"></i>
        <span>我的</span>
      </div>
    </footer>
  </div>
</template>



<script>
import Footer from '../components/Footer.vue';
export default {
  name: 'Payment',
  data() {
    return {
      id: this.$route.query.orderId,
      orderDetails: [],
      isShowDetailet: false,
      // 修复bug：新增user对象，用于存储当前用户信息
      user: {},
      business: {},
      order: {},
      totalPrice: 0,
      selectedPaymentMethod: 1, 
      wallet: {},
      consumption: [0,500,2000,5000,12000,30000]
    }
  },

  created() {
    //获取token
    this.token = localStorage.getItem('token');
    //获取user
    this.$axios.get(`/user`, {
      headers: {
        'Authorization': `Bearer ${this.token}`
      }
    }).then(response => {
      this.user = response.data.data;
    }).catch(error => {
      console.error(error);
    });

    this.$axios.get(`/orders/${this.id}`, {
      headers: {
        'Authorization': `Bearer ${this.token}`
      }
    }).then(response => {
      this.orderDetails = response.data.data.orderdetailetList;
      this.business = response.data.data.business;
      this.order = response.data.data;
      this.totalPrice=this.order.orderTotal;

      this.$axios.get('/wallet', {
        headers: {
          'Authorization': `Bearer ${this.token}`
        }
      }).then(response => {
        this.wallet = response.data
      }).catch(error => {
        console.error('获取钱包信息失败:', error)
        ElMessage.error('获取钱包信息失败')
      });


    }).catch(error => {
      console.error(error);
    });
  },

  mounted() {
    //这里的代码是实现：一旦路由到在线支付组件，就不能回到订单确认组件。
    //先将当前url添加到history对象中
    history.pushState(null, null, document.URL);
    //popstate事件能够监听history对象的变化
    window.onpopstate = () => {
      this.$router.push({ path: '/index' });
    }
  },
  destroyed() {
    window.onpopstate = null;
  },
  methods: {

    toPay() {
      let overdraft=this.consumption[this.wallet.vip]-this.wallet.overdraft;
      console.log('可透支钱数：'+overdraft);
      console.log('透支额度：'+this.consumption[this.wallet.vip]);
      console.log('已透支：'+this.wallet.overdraft);
      if(this.selectedPaymentMethod==2){
        if(overdraft < this.totalPrice){
          alert('透支额度不足，请选择余额支付或充值');
          return;
        }
      }else{
        if(this.wallet.balance>=this.totalPrice){
          // 余额充足，继续支付流程
        }else if(this.wallet.balance+overdraft>=this.totalPrice){
          // 余额不足但透支额度足够，提示用户将使用透支支付
          if(!confirm('余额不足，不足部分是否使用透支支付？')){
            return;
          }
        }else{
            alert('余额不足，请充值');
            return; // 用户取消支付
        }
      }

      this.$axios.put(`orders/pay/${this.id}/${this.selectedPaymentMethod}`, {}, {
        headers: {
          'Authorization': `Bearer ${this.token}`
        }
      }).then(response => {
        if (response.data.success === true) {
          alert('支付成功！');
          // 支付成功后跳转到订单列表页面
          this.$router.push({ path: '/orderList' });
        } else {
          alert('支付失败，请重试');
        }
      }).catch(error => {
        console.error('支付请求失败:', error);
        alert('支付请求失败');
      });
    },
    detailetShow() {
      this.isShowDetailet = !this.isShowDetailet;
    }
  },
  components: {
    Footer
  }
}



</script>
<style scoped>
/****************** 总容器 ******************/
.wrapper {
  width: 100%;
  height: 100%;
}

/****************** header部分 ******************/
.wrapper header {
  width: 100%;
  height: 12vw;
  background-color: #0097FF;
  color: #fff;
  font-size: 4.8vw;
  position: fixed;
  left: 0;
  top: 0;
  z-index: 1000;
  display: flex;
  justify-content: center;
  align-items: center;
}

/****************** 订单信息部分 ******************/
.wrapper h3 {
  margin-top: 12vw;
  box-sizing: border-box;
  padding: 4vw 4vw 0;
  font-size: 4vw;
  font-weight: 300;
  color: #999;
}

.wrapper .order-info {
  box-sizing: border-box;
  padding: 4vw;
  font-size: 4vw;
  color: #666;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.wrapper .order-info p:last-child {
  color: orangered;
}

/****************** 订单明细部分 ******************/
.wrapper .order-detailet {
  width: 100%;
}

.wrapper .order-detailet li {
  width: 100%;
  box-sizing: border-box;
  padding: 1vw 4vw;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.wrapper .order-detailet li p {
  font-size: 3vw;
  color: #666;
}

/****************** 支付方式部分 ******************/
.wrapper .payment-type {
  width: 100%;
}

.wrapper .payment-type li {
  width: 100%;
  box-sizing: border-box;
  padding: 4vw;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.wrapper .payment-type li img {
  width: 33vw;
  height: 8.9vw;
}

.wrapper .payment-type li .fa-check-circle {
  font-size: 5vw;
  color: #38CA73;
}

.wrapper .payment-button {
  width: 100%;
  box-sizing: border-box;
  padding: 4vw;
}

.wrapper .payment-button button {
  width: 100%;
  height: 10vw;
  border: none;
  /*去掉外轮廓线*/
  outline: none;
  border-radius: 4px;
  background-color: #38CA73;
  color: #fff;
}

/* 底部导航 */
.bottom-nav {
  position: fixed;
  bottom: 0;
  left: 0;
  width: 100%;
  height: 16vw;
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  border-top: 1px solid #e0e0e0;
  display: flex;
  justify-content: space-around;
  align-items: center;
  z-index: 100;
}

.nav-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  color: #999;
  font-size: 3vw;
  cursor: pointer;
  transition: all 0.3s ease;
  padding: 2vw;
  border-radius: 10px;
}

.nav-item.active {
  color: #0097FF;
  transform: translateY(-3px);
}

.nav-item i {
  font-size: 5.5vw;
  margin-bottom: 1vw;
  transition: all 0.3s ease;
}

.nav-item.active i {
  transform: scale(1.2);
}

.nav-item span {
  font-size: 3vw;
  font-weight: 500;
}
.payment-type li {
  width: 100%;
  box-sizing: border-box;
  padding: 4vw;
  display: flex;
  justify-content: space-between;
  align-items: center;
  cursor: pointer;
  transition: all 0.3s ease;
}

.payment-type li:hover {
  background-color: #f5f5f5;
}

.payment-option {
  display: flex;
  align-items: center;
}

.payment-option i {
  font-size: 5vw;
  margin-right: 3vw;
  color: #0097FF;
}

.payment-info {
  display: flex;
  flex-direction: column;
}

.payment-title {
  font-size: 4vw;
  color: #333;
  font-weight: 600;
}

.payment-desc {
  font-size: 3vw;
  color: #999;
  margin-top: 1vw;
}
</style>